package com.zuowei.ycy.user.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.and.yzy.frame.util.DateTool;
import com.and.yzy.frame.util.RetrofitUtils;
import com.and.yzy.frame.view.listview.ListViewForScrollView;
import com.bigkoo.pickerview.OptionsPickerView;
import com.zuowei.ycy.R;
import com.zuowei.ycy.user.adapter.OrderCommitAdapter;
import com.zuowei.ycy.user.config.UserManger;
import com.zuowei.ycy.user.domain.AddressInfo;
import com.zuowei.ycy.user.domain.BusinessSortInfo;
import com.zuowei.ycy.user.event.AddressEvent;
import com.zuowei.ycy.user.http.Address;
import com.zuowei.ycy.user.http.Order;
import com.zuowei.ycy.ui.BaseToolbarAty;
import com.zuowei.ycy.user.ui.mine.AddressListAty;
import com.zuowei.ycy.user.util.AppJsonUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * 提交订单
 */
public class CommitOrderAty extends BaseToolbarAty {
    @Bind(R.id.lv_data)
    ListViewForScrollView mLv;
    @Bind(R.id.tv_time)
    TextView mTvTime;
    @Bind(R.id.tv_name)
    TextView mTvName;
    @Bind(R.id.tv_phone)
    TextView mTvPhone;
    @Bind(R.id.tv_address)
    TextView mTvAddress;
    @Bind(R.id.ll_have_address)
    LinearLayout mLlHaveAddress;
    @Bind(R.id.ll_empty)
    LinearLayout mLlEmpty;
    @Bind(R.id.et_beizhu)
    EditText mEtBeizhu;
    @Bind(R.id.tv_take_price)
    TextView mTvTakePrice;
    @Bind(R.id.tv_price)
    TextView mTvPrice;

    @Bind(R.id.tv_price_2)
    TextView mTvPrice2;

    @Bind(R.id.tv_number)
    TextView mTvNumber;


    private String address_id = "-1";
    private OptionsPickerView pvOptions;

    private String merchant_id;

    private String goods_json;

    private String delivery_time = "0";
    private String time;

    @Override
    public int getLayoutId() {
        return R.layout.index_commit_order_layout;
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);


        mToolbar.setTitle("提交订单");

        mTvPrice.setText("￥" + getIntent().getExtras().getString("price"));
        mTvPrice2.setText("￥" + getIntent().getExtras().getString("price"));
        mTvTakePrice.setText("￥" + getIntent().getExtras().getDouble("delivery_fee"));
        mTvNumber.setText("共" + getIntent().getExtras().getString("count") + "份");

        merchant_id = getIntent().getExtras().getString("merchant_id");


        List<BusinessSortInfo> infos = getIntent().getExtras().getParcelableArrayList("data");


        OrderCommitAdapter commitAdapter = new OrderCommitAdapter(this, infos, R.layout.index_commit_order_lv_item);
        mLv.setAdapter(commitAdapter);


        StringBuffer buffer = new StringBuffer();

        buffer.append("[");
        for (BusinessSortInfo info : infos) {
            buffer.append("{\"goods_id\":\"" + info.getGoods_id() + "\",\"number\":\"" + info.getNumber() + "\"");

            buffer.append("},");
        }
        buffer.delete(buffer.length() - 1, buffer.length());
        buffer.append("]");


        goods_json = buffer.toString();


    }

    List<Long> longList;
    ArrayList<String> times;

    private void initTime() {


        times = new ArrayList<>();
        times.add("立即送出");

        //得到今天晚上22:00的时间
        Date date = new Date();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        time = format.format(date);
        String lastTimestr = format.format(date) + " 22:00:00";
        long lastTime = DateTool.strTimeToTimestamp(lastTimestr);
        //得到现在的分钟
        int newMin = Integer.parseInt(DateTool.getNowMin());

        //化成10的倍数
        if (newMin % 10 != 0) {
            newMin = newMin + (10 - newMin % 10);
        }

        String newTiemStr = DateTool.timesToStrTime(System.currentTimeMillis() + "", "yyyy-MM-dd HH:") + newMin + ":00";


        long newTime = DateTool.strTimeToTimestamp(newTiemStr);

        longList = new ArrayList<>();


        while (newTime < lastTime) {
            longList.add(newTime);

            newTime += 20 * 60 * 1000L;
        }

        longList.add(lastTime);

        for (int i = 0; i < longList.size(); i++) {
            times.add(DateTool.timesToStrTime(longList.get(i) + "", "HH:mm"));
        }
        pvOptions.setPicker(times);
        pvOptions.setCyclic(false, false, false);
    }

    @Override
    public boolean setIsInitRequestData() {
        return true;
    }

    @OnClick({R.id.rl_time, R.id.tv_commit, R.id.ll_empty, R.id.ll_have_address})
    @Override
    public void btnClick(View view) {
        super.btnClick(view);
        switch (view.getId()) {
            case R.id.rl_time:
                if (pvOptions == null) {

                    pvOptions = new OptionsPickerView(this);
                    pvOptions.setTitle("送达时间");
                    initTime();
                    pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3) {


                            mTvTime.setText(times.get(options1));

                            if (times.get(options1).equals("立即送出")) {
                                delivery_time = "0";
                            } else {
                                delivery_time = time + " " + times.get(options1);
                            }

                        }
                    });

                }
                pvOptions.show();

                break;

            case R.id.tv_commit:
                if (address_id.equals("-1")) {
                    showToast("请选择地址");
                    return;
                }
                showLoadingDialog(null);
                doHttp(RetrofitUtils.createApi(Order.class).addOrder(UserManger.getM_id(), merchant_id, delivery_time, mEtBeizhu.getText().toString().trim(), goods_json, address_id), 2);

                break;
            case R.id.ll_empty:
                startActivityForResult(AddressListAty.class, new Bundle(), 1);
                break;
            case R.id.ll_have_address:
                startActivityForResult(AddressListAty.class, new Bundle(), 1);
                break;


        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(AddressEvent event) {
        //如果地址被删除了
        if (event.getAddress_id().equals(address_id)) {
            mLlEmpty.setVisibility(View.VISIBLE);
            mLlHaveAddress.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();

            AddressInfo info = (AddressInfo) bundle.getSerializable("info");
            address_id = info.getAddress_id();

            mLlEmpty.setVisibility(View.GONE);
            mLlHaveAddress.setVisibility(View.VISIBLE);

            mTvName.setText(info.getConsignee());
            mTvPhone.setText(info.getMobile());
            mTvAddress.setText(info.getAddress());

        }


        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void requestData() {

        showLoadingContentDialog();
        doHttp(RetrofitUtils.createApi(Address.class).getOneAddress(UserManger.getM_id()),1);

    }

    @Override
    public void onSuccess(String result, Call<ResponseBody> call, Response<ResponseBody> response, int what) {

        switch (what) {
            case 1:
                try {
                    AddressInfo info= AppJsonUtil.getObject(result,AddressInfo.class);
                    address_id = info.getAddress_id();
                    mLlEmpty.setVisibility(View.GONE);
                    mLlHaveAddress.setVisibility(View.VISIBLE);
                    mTvName.setText(info.getConsignee());
                    mTvPhone.setText(info.getMobile());
                    mTvAddress.setText(info.getAddress());

                } catch (Exception e) {
                    e.printStackTrace();
                    mLlEmpty.setVisibility(View.VISIBLE);
                    mLlHaveAddress.setVisibility(View.GONE);

                }


                break;
            case 2:

                Bundle bundle=new Bundle();
                bundle.putString("price", AppJsonUtil.getString(result,"order_price"));
                bundle.putString("order_sn", AppJsonUtil.getString(result,"order_sn"));
                bundle.putString("order_id", AppJsonUtil.getString(result,"order_id"));

                startActivity(PayOrderAty.class, bundle);
                setHasAnimiation(false);
                finish();
                break;

        }


        super.onSuccess(result, call, response, what);
    }
}
